"""Codex审查工作流的MCP服务器，提供完整的工作流管理。"""

import os
import sys
import asyncio
from pathlib import Path
from typing import Any

# Fix import path for both module and direct execution
current_dir = Path(__file__).parent
if str(current_dir) not in sys.path:
    sys.path.insert(0, str(current_dir))

from mcp.server import InitializationOptions, NotificationOptions, Server
from mcp.types import Tool, TextContent
from pydantic import BaseModel, Field
from mcp.server.stdio import stdio_server

# Try relative import first, fallback to absolute
try:
    from .workflow_manager import CodexWorkflowManager
except ImportError:
    from workflow_manager import CodexWorkflowManager


class StartReviewArgs(BaseModel):
    """start_review工具的参数"""
    review_request_path: str = Field(
        description="ClaudeCode生成的review_request.md临时文件绝对路径（应使用UTF-8编码，推荐无BOM）"
    )
    draft_path: str = Field(
        description="ClaudeCode生成的draft.md临时文件绝对路径（应使用UTF-8编码，推荐无BOM）"
    )
    project_root: str = Field(description="项目根目录绝对路径（必需参数，由ClaudeCode传递）")
    max_iterations: int = Field(default=3, description="最大迭代轮次（未来扩展），默认3轮")
    timeout_seconds: int = Field(default=1800, description="超时时间（秒），默认1800秒（30分钟）")


# Initialize MCP server
app = Server("codex-review-mcp")

# workflow_manager will be created per-request with project_root


@app.list_tools()
async def list_tools() -> list[Tool]:
    """列出可用的MCP工具"""
    return [
        Tool(
            name="start_review",
            description=(
                "启动Codex审查工作流：创建session目录、复制文件、启动codex进程、监控进度、解析报告"
            ),
            inputSchema=StartReviewArgs.model_json_schema()
        )
    ]


@app.call_tool()
async def call_tool(name: str, arguments: Any) -> list[TextContent]:
    """处理MCP工具调用

    Args:
        name: 工具名称（"start_review"）
        arguments: 工具参数（StartReviewArgs）

    Returns:
        包含审查结果的TextContent列表
    """
    if name != "start_review":
        raise ValueError(f"Unknown tool: {name}")

    args = StartReviewArgs(**arguments)

    # Create workflow_manager instance with project_root
    workflow_manager = CodexWorkflowManager(
        base_dir="ClaudeCodexTasks",
        project_root=args.project_root
    )

    # Start review workflow
    try:
        result = await workflow_manager.start_review(
            review_request_path=args.review_request_path,
            draft_path=args.draft_path,
            max_iterations=args.max_iterations,
            timeout_seconds=args.timeout_seconds
        )

        # Format result as text response
        # If review completed and parsed, use parsed status; otherwise use execution status
        if result.parsed:
            review_status = result.parsed.status
            status_emoji = {
                "approved": "[APPROVED]",
                "major_issues": "[MAJOR_ISSUES]",
                "minor_issues": "[MINOR_ISSUES]"
            }.get(review_status, "[UNKNOWN]")
        else:
            review_status = result.status
            status_emoji = {
                "completed": "[SUCCESS]",
                "timeout": "[TIMEOUT]",
                "failed": "[FAILED]"
            }.get(review_status, "[UNKNOWN]")

        response_text = f"""{status_emoji} Review {review_status}

**Execution Time**: {result.execution_time} seconds
**Session Directory**: {result.session_dir or 'N/A'}

**Review Report**:
{result.report_content}

**Codex Log (last 10 lines)**:
{result.log_tail}
"""
        return [TextContent(type="text", text=response_text)]

    except Exception as e:
        error_text = f"[ERROR] Review workflow failed: {str(e)}"
        return [TextContent(type="text", text=error_text)]


async def async_main():
    """MCP服务器异步主入口"""
    async with stdio_server() as (read_stream, write_stream):
        await app.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="codex-review-mcp",
                server_version="1.0.0",
                capabilities=app.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                )
            )
        )


def main():
    """同步入口（由uv调用）"""
    asyncio.run(async_main())


if __name__ == "__main__":
    main()
